package com.ys.mq;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ys.constant.ShopCode;
import com.ys.entity.MQEntity;;
import com.ys.pojo.TradeOrder;
import com.ys.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}",
        consumerGroup = "${mq.order.consumer.group.name}",
        messageModel = MessageModel.BROADCASTING)
public class OrderRockerMQListener implements RocketMQListener<MessageExt> {
   /* @Autowired
    private OrderMapper orderMapper;*/
    @Autowired
    private OrderService orderService;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String body = new String(messageExt.getBody(), "UTF-8");

            MQEntity mqEntity = JSON.parseObject(body, MQEntity.class);

            log.info("收到消息");
            //找到对应的订单
          /*  QueryWrapper<TradeOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TradeOrder::getOrderId,mqEntity.getOrderId())
                                    .eq(TradeOrder::getGoodsId,mqEntity.getGoodsId())
                                    .eq(TradeOrder::getUserId,mqEntity.getUserId());
            TradeOrder tradeOrder = orderMapper.selectOne(queryWrapper);*/

            //更新订单状态
            UpdateWrapper<TradeOrder> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().set(TradeOrder::getOrderStatus, ShopCode.SHOP_ORDER_CANCEL.getCode())
                                    .eq(TradeOrder::getOrderId,mqEntity.getOrderId())
                                    .eq(TradeOrder::getGoodsId,mqEntity.getGoodsId())
                                    .eq(TradeOrder::getUserId,mqEntity.getUserId());
            orderService.update(updateWrapper);
            log.info("订单:["+mqEntity.getOrderId()+"]状态设置为取消");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.info("订单取消发生异常");
        }
    }
}
